<template>
  <div class="p-2 modal_main">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" size="small" label-width="80">
            <el-form-item label="机型" prop="modelType">
              <el-select v-model="queryParams.modelType" clearable>
                <el-option v-for="(item, index) in pageAircraftTypes" :key="'type' + index" :label="item.label" :value="item.label" />
              </el-select>
            </el-form-item>
            <el-form-item label="载荷类型" prop="loadName">
              <el-select v-model="queryParams.loadName" clearable @change="handleLoadNameChange">
                <el-option v-for="(item, index) in pageLoadNames" :key="'type' + index" :label="item.label" :value="item.label" />
              </el-select>
            </el-form-item>
            <el-form-item label="载荷分类" prop="loadType">
              <el-select v-model="queryParams.loadType" clearable>
                <el-option v-for="(item, index) in pageLoadTypes" :key="'name' + index" :label="item.label" :value="item.label" />
              </el-select>
            </el-form-item>
            <el-form-item label="阶段" prop="stage">
              <el-select v-model="queryParams.stage" clearable>
                <el-option v-for="(item, index) in pageStages" :key="'stage' + index" :label="item.label" :value="item.label" />
              </el-select>
            </el-form-item>
            <el-form-item label="版本号" prop="version">
              <el-input v-model="queryParams.version" placeholder="请输入版本号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="轮次" prop="round">
              <el-input v-model="queryParams.round" placeholder="请输入轮次" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="state">
              <el-select v-model="queryParams.state" clearable>
                <el-option v-for="(item, index) in pageStates" :key="'state' + index" :label="item.label" :value="item.label" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建日期">
              <el-date-picker
                v-model="dateRangeCreateTime"
                style="width: 240px"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              ></el-date-picker>
            </el-form-item>
            <el-form-item style="padding-left: 80px">
              <el-button size="small" type="primary" @click="handleQuery">查询</el-button>
              <el-button size="small" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['version:management:add']" size="small" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-if="showTable" v-loading="loading" :data="tableDatas">
        <el-table-column label="序号" width="50" type="index" align="center">
          <template #default="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="机型" align="center" prop="modelType" width="100"> </el-table-column>
        <el-table-column label="载荷类型" align="center" prop="loadName" width="180"> </el-table-column>
        <el-table-column label="载荷分类" align="center" prop="loadType"> </el-table-column>
        <el-table-column label="阶段" align="center" prop="stage"> </el-table-column>
        <el-table-column label="版本号" align="center" prop="version" />
        <el-table-column label="轮次" align="center" prop="round" />
        <el-table-column label="状态" align="center" prop="state" width="200"> </el-table-column>
        <el-table-column label="创建人" align="center" prop="createBy" />
        <el-table-column label="创建日期" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实验次数" align="center" prop="experimentCount" />
        <el-table-column label="操作" align="center" width="230">
          <template #default="scope">
            <el-button v-hasPermi="['version:management:detail']" size="small" link type="primary" @click="handleDetail(scope.row)">详情</el-button>
            <el-button
              v-hasPermi="['version:management:edit']"
              size="small"
              link
              type="primary"
              :disabled="scope.row.state !== '使用中' || scope.row.experimentCount !== 0"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              v-hasPermi="['version:management:upgrade']"
              size="small"
              link
              type="primary"
              :disabled="scope.row.state === '已作废' || scope.row.experimentCount === 0"
              @click="handleUpgrade(scope.row)"
              >升版</el-button
            >
            <el-button
              v-hasPermi="['version:management:cancel']"
              size="small"
              link
              type="primary"
              :disabled="scope.row.state === '已作废'"
              @click="handleRemove(scope.row)"
              >作废</el-button
            >
            <el-button
              v-hasPermi="['version:management:delete']"
              size="small"
              link
              type="primary"
              :disabled="scope.row.state === '已作废' || scope.row.experimentCount > 0"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagenation">
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          layout="prev, pager, next,jumper"
          :total="total"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 新增/升版 -->
    <el-dialog v-if="detailDialogShow" v-model="detailDialogShow" :title="title" width="1000px" append-to-body :before-close="handleDialogClose">
      <el-steps :active="active" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="参数设置"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <VersionBasicForm v-if="active === 0" ref="versionBasicFormRef" :data-id="dataId" :type="type" />
      <VersionDetailForm v-if="active === 1" ref="versionDetailFormRef1" key="setting" :data-id="dataId" :old-id="oldId" :type="type" />
      <VersionDetailForm v-if="active === 2" ref="versionDetailFormRef2" key="complate" :data-id="dataId" type="complate" />
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="active === 1" type="primary" @click="handlePreClick"> 上一步</el-button>
          <el-button v-if="active !== 2" type="primary" @click="handleNextClick"> 下一步</el-button>
          <el-button v-if="active === 2" type="primary" @click="handleComplateClick"> 完成</el-button>
          <el-button v-if="active !== 2" @click="handleDialogClose">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 详情、编辑 -->
    <el-dialog v-if="detailDialogShow2" v-model="detailDialogShow2" :title="title" width="1000px" append-to-body>
      <VersionDetailForm key="detail" ref="versionDetailFormRef3" :type="type" :data-id="dataId" />
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="type === 'edit'" type="primary" @click="handleSureClick">确定</el-button>
          <el-button @click="handleDialogClose2">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="LoadVersionManagement" lang="ts">
import { optionType } from '@/api/loadProcessingAlgorithm/type';
import { loadNames, stages, versionStates, aircraftTypes } from '@/api/loadProcessingAlgorithm/index';
import {
  getVersionList,
  deleteVersion,
  removeVersion,
  deletePublicParameter,
  deleteSpecificParameter
} from '@/api/loadProcessingAlgorithm/loadVersionManagement/index';
import { dataForm, dataQuery, dataVO } from '@/api/loadProcessingAlgorithm/loadVersionManagement/type';
import { getToken } from '@/utils/auth';
import VersionBasicForm from './versionBasicForm.vue';
import VersionDetailForm from './versionDetailForm.vue';
import setting from '@/settings';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const tableDatas = ref<dataVO[]>([]);
const showTable = ref(true);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const versionBasicFormRef = ref(null);
const versionDetailFormRef1 = ref(null);
const versionDetailFormRef2 = ref(null);
const versionDetailFormRef3 = ref(null);
const detailDialogShow = ref(false);
const detailDialogShow2 = ref(false);
const publicIds = ref([]);
const specificIds = ref([]);
const dataId = ref('');
const title = ref('');
const oldId = ref('');
const type = ref('add');
const active = ref(0);
const flag = ref(0); // 0 编辑 1 编辑完成 2 参数配置完成
const pageLoadNames = ref(loadNames);
const pageLoadTypes = ref([]);
const pageStages = ref(stages);
const pageStates = ref(versionStates);
const pageAircraftTypes = ref(aircraftTypes);
const queryParams = reactive<dataQuery>({
  pageNum: 1,
  pageSize: 10,
  loadName: '',
  loadType: '',
  stage: '',
  version: '',
  state: '',
  modelType: '',
  round: '',
  beginCreateTime: '',
  endCreateTime: '',
  orderByColumn: 'CreateTime',
  isAsc: 'desc'
});
const handleLoadNameChange = () => {
  if (queryParams.loadName) {
    const obj = pageLoadNames.value.find((item) => item.label === queryParams.loadName);
    pageLoadTypes.value = obj.children;
  } else {
    pageLoadNames.value.forEach((item) => {
      pageLoadTypes.value = [...pageLoadTypes.value, ...item.children];
    });
  }
};
const handleAdd = () => {
  flag.value = 0;
  dataId.value = '';
  active.value = 0;
  oldId.value = '';
  type.value = 'add';
  title.value = '新增版本';
  detailDialogShow.value = true;
};
// 查看详情
const handleDetail = (data) => {
  dataId.value = data.id;
  type.value = 'view';
  oldId.value = '';
  title.value = '详情';
  detailDialogShow2.value = true;
};
const handleEdit = (data) => {
  dataId.value = data.id;
  type.value = 'edit';
  title.value = '编辑';
  detailDialogShow2.value = true;
};
const handleUpgrade = (data) => {
  flag.value = 0;
  dataId.value = data.id;
  active.value = 0;
  oldId.value = data.id;
  type.value = 'upgrade';
  title.value = '升版';
  detailDialogShow.value = true;
};
const getLabelByValue = (arr, value) => {
  const obj = arr.find((item) => item.value === value);
  if (obj) {
    return obj.label;
  } else {
    return value;
  }
};
const getloadNameByValue = (row) => {
  const obj = pageLoadNames.value.find((item) => item.value === row.loadType);
  if (obj) {
    const newObj = obj.children.find((el) => el.value === row.loadName);
    if (newObj) {
      return newObj.label;
    }
  }
  return row.loadName;
};
/** 查询模型列表 */
const getList = async () => {
  loading.value = true;
  if (dateRangeCreateTime.value.length) {
    queryParams.beginCreateTime = dateRangeCreateTime.value[0];
    queryParams.endCreateTime = dateRangeCreateTime.value[1];
  } else {
    queryParams.beginCreateTime = '';
    queryParams.endCreateTime = '';
  }
  const response = await getVersionList(queryParams);
  tableDatas.value = response.rows;
  total.value = response.total;
  loading.value = false;
  showTable.value = true;
};
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  showTable.value = false;
  dateRangeCreateTime.value = [];
  queryFormRef.value?.resetFields();
  handleQuery();
}
/** 删除按钮操作 */
const handleRemove = async (row?) => {
  const ids = row?.id;
  await proxy?.$modal.confirm('是否确认作废该数据项?');
  loading.value = true;
  await removeVersion(ids).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('作废成功');
};
/** 删除按钮操作 */
const handleDelete = async (row?) => {
  const ids = row?.id;
  await proxy?.$modal.confirm('是否确认删除该数据项?');
  loading.value = true;
  await deleteVersion(ids).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};
const handlePreClick = () => {
  if (flag.value === 2) {
    specificIds.value = versionDetailFormRef2.value.getSpecificParamIds();
    publicIds.value = versionDetailFormRef2.value.getPublicParamIds();
  }
  active.value -= 1;
};
const handleNextClick = async () => {
  if (active.value === 0 && flag.value === 0) {
    const res = await versionBasicFormRef.value.submitData();
    if (res) {
      dataId.value = res;
      active.value += 1;
      flag.value = 1;
    }
  } else if (active.value === 1 && flag.value === 1) {
    const res = await versionDetailFormRef1.value.submitData();
    if (res) {
      active.value += 1;
      flag.value = 2;
      oldId.value = '';
    }
  } else {
    active.value += 1;
  }
};
const handleSureClick = async () => {
  const res = await versionDetailFormRef3.value.submitData();
  if (res) {
    proxy?.$modal.msgSuccess('编辑完成！');
    detailDialogShow2.value = false;
    getList();
  }
};
const handleComplateClick = () => {
  proxy?.$modal.msgSuccess('创建完成！');
  detailDialogShow.value = false;
  getList();
};
const handleDialogClose = async () => {
  if (flag.value === 1) {
    await proxy?.$modal.confirm('取消将删除已创建的版本信息，是否继续?');
    await deleteVersion(dataId.value);
    await getList();
    detailDialogShow.value = false;
  } else if (flag.value === 2) {
    await proxy?.$modal.confirm('取消将删除已创建的版本信息和配置的参数信息，是否继续?');
    await deleteVersion(dataId.value);
    if (publicIds.value.length) {
      deletePublicParameter(publicIds.value.join(','));
    }
    if (specificIds.value.length) {
      deleteSpecificParameter(specificIds.value.join(','));
    }
    detailDialogShow.value = false;
  } else {
    detailDialogShow.value = false;
  }
};
const handleDialogClose2 = () => {
  detailDialogShow2.value = false;
};
onMounted(() => {
  handleLoadNameChange();
  getList();
});
</script>
<style lang="scss" scoped>
.modal_main {
  height: calc(100vh - 84px);
  overflow: auto;
}
.pagenation {
  display: flex;
  justify-content: end;
  margin-top: 10px;
}
.dialog-footer {
  text-align: center;
}
:deep(.el-upload) {
  display: block;
}
</style>
